"""导入Django框架包"""
import hashlib
import uuid

from django.shortcuts import render, redirect, HttpResponse
from django.views import View
from django.db.models import Q

"""导入python包"""
from datetime import datetime
import json, os, hashlib, xlrd

"""导入数据库"""
from logistics.MessagePushOperationRecords import RecordAndPush
from administrative.models import Company, Topicsattachments
from personal_center.models import MakeCopy, User
from Oa_system.models import Staffing
from logistics.models import *
from announcements import public_file
from administrative.public_file import ParseWord, PDFConverter


def trade_union_upload_file(request, obj, file_type):
    file_lenth = request.POST.get('file_lenth', '')
    for i in range(int(file_lenth)):
        files = request.FILES.get(f'file{i}')
        file_obj = Topicsattachments.objects.create(
            topics_number=obj.fj_number, file_size=public_file.StrOfSize(files.size), file_path=files, uploader=request.user.username,
            uploader_user=request.user, file_type=file_type, is_deleted=False, source='LZSQ'
        )
        sys_path = os.getcwd()
        file_name = files.name
        file_obj.file_name = file_name
        file_obj.save()

        word_path = sys_path + '/media/' + str(file_obj.file_path)
        old_word_path = word_path
        temp_name = os.path.splitext(file_name)[0]
        new_word_path = old_word_path.replace(
            os.path.splitext(file_obj.file_path.name.split("/")[-1])[0], temp_name)
        os.rename(old_word_path, new_word_path)
        word_path = new_word_path

        file_path = file_obj.file_path.name.replace(
            os.path.splitext(file_obj.file_path.name.split("/")[-1])[0], temp_name)

        if word_path.split('.')[-1] in ['docx', 'doc', 'DOC', 'DOCX']:
            pdf_path = ParseWord().word2pdf(word_path)
        elif word_path.split(".")[-1] in ['ppt', 'pptx']:
            pdf_path = ParseWord().ppt2pdf(word_path)
        elif word_path.split(".")[-1] in ['xls', 'xlsx', 'XLS', 'XLSX']:
            b = xlrd.open_workbook(word_path)
            sheetnum = len(b.sheets())
            pdfConverter = PDFConverter(word_path, sheetnum, os.path.splitext(file_name)[0])
            pdf_path = pdfConverter.run_conver()
        else:
            pdf_path = '/media/' + str(file_path)
        pdf_list = []
        if type(pdf_path) is list:
            for i in range(len(pdf_path)):
                if i == 0:
                    file_obj.pdf_path = pdf_path[i].replace(os.getcwd(), '')
                    tic_id = file_obj.id
                    file_obj.save()
                else:
                    all_file = Topicsattachments.objects.create(topics_number=obj.fj_number, file_path=files, file_size=public_file.StrOfSize(files.size),
                                                                uploader=request.user.username, file_type=1, pdf_path=pdf_path[i].replace(os.getcwd(), ''),
                                                                file_name=os.path.split(pdf_path[i])[1], source="HQWZCG", uploader_user=request.user.username)
                    tic_id = all_file.id
                one_dict = {"id": tic_id, 'pdf_path': pdf_path[i].replace(os.getcwd(), '')}
                pdf_list.append(one_dict)
        else:
            fileName = pdf_path.split("/")[-1].split(".")[0]
            pdf_path = pdf_path.replace(fileName, files.name.split(".")[0]).replace(os.getcwd(), "")
            pdf_path = pdf_path.replace(os.path.splitext(os.path.split(pdf_path)[1])[0], os.path.splitext(file_name)[0])
            file_obj.pdf_path = pdf_path
            file_obj.save()


"""服务采购申请流程"""
class ServiceProcurementList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'logistics/ServiceProcurementList.html', {'realname': real_name, 'position': position, 'department': department, "table_name": "PurchasingRequisition"})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_value", '')
        objs = PurchasingRequisition.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(company__name__contains=search_value), apply_user=request.user).order_by('-create_time')

        data_list = [
            {'id': obj.id, 'apply_user': obj.apply_user.real_name, 'create_time': obj.create_time.strftime("%Y-%m-%d"), 'ApplicationReason': obj.ApplicationReason,
             'ApplicationType': obj.ApplicationType, 'BudgetAmount': obj.BudgetAmount, 'state': obj.get_state_str(), 'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'url': f"<a href='ServiceProcurementDraft.html?id={obj.id}'>编辑</a>" if obj.get_state_str() == '草稿'
             else (f"<a href='ServiceProcurementDetail.html?id={obj.id}'>查看</a> | <a href='ServiceProcurementDetail.html?revise=true&id={obj.id}'>修改</a>" if (obj.can_revise == '1' and obj.state in ['one', 'two', 'three', 'four'])
             else (f"<a href='ServiceProcurementDetail.html?id={obj.id}'>查看</a>" if obj.state == 'stop'
             else f"<a href='ServiceProcurementDetail.html?id={obj.id}'>查看</a>"))} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ServiceProcurementIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        ReturnData = {'realname': real_name, 'position': position, 'department': department, "applicat_time": datetime.now().strftime("%Y-%m-%d"),
                      "Telephone": request.user.mobile, "uuid": uuid.uuid4()}
        return render(request, 'logistics/ServiceProcurementIndex.html', ReturnData)

    def post(self, request):
        applic_id = request.POST.get("id", '')
        ApplicationReason = request.POST.get("ApplicationReason", '')
        ApplicationType = request.POST.get("ApplicationType", '')
        ServiceContent = request.POST.get("ServiceContent", '')
        BudgetAmount = request.POST.get("BudgetAmount", '')
        AmountWords = request.POST.get("AmountWords", '')
        fj_number = request.POST.get('fj_number', '')
        admin_flag = request.POST.get("admin", '')
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "服务采购")
        except:
            pass
        if applic_id:
            obj = PurchasingRequisition.objects.get(id=applic_id)
            obj.ApplicationReason = ApplicationReason
            obj.ApplicationType = ApplicationType
            obj.ServiceContent = ServiceContent
            obj.BudgetAmount = BudgetAmount
            obj.AmountWords = AmountWords
            obj.save()
            message_str = "修改成功！"
        else:
            obj = PurchasingRequisition.objects.create(apply_user=request.user, ApplicationReason=ApplicationReason, ApplicationType=ApplicationType, company=request.user.company,
                                                       ServiceContent=ServiceContent, BudgetAmount=BudgetAmount, AmountWords=AmountWords, fj_number=fj_number)
            message_str = "创建成功！"

        if not admin_flag:
            obj.current_audit_users.clear()
            obj.purchasingrequisitionrecord_set.filter(state='unaudit').delete()

            one_appave = request.user.company.head_people
            flag = True
            if request.user != one_appave:
                PurchasingRequisitionRecord.objects.create(node='one', state='unaudit', audit_people=one_appave, purchasing_requisition_id=obj)
                flag = False
                obj.state = "one"
                obj.current_audit_users.add(one_appave)

            two_appave = request.user.company.leaders_id
            PurchasingRequisitionRecord.objects.create(node='two', state='unaudit', audit_people=two_appave, purchasing_requisition_id=obj)
            if flag:
                obj.state = "two"
                obj.current_audit_users.add(two_appave)

            three_appave = Company.objects.get(id=27).head_people
            PurchasingRequisitionRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, purchasing_requisition_id=obj)

            four_appave = Company.objects.get(id=27).leaders_id
            PurchasingRequisitionRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, purchasing_requisition_id=obj)
            obj.save()
            # ********************************************** 发送小程序推送 ******************************************
            topic_type = "服务采购"
            applicant = obj.apply_user.real_name
            ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = obj.ApplicationReason[:15] + "……" if len(
                obj.ApplicationReason) > 15 else obj.ApplicationReason
            for jj in obj.current_audit_users.all():
                try:
                    RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
        returnData = {'code': 200, 'message': message_str}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class ServiceProcurementDraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = PurchasingRequisition.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post, 'file_list': file_list,
                   'department': request.user.company.name, 'obj': obj, "audit_dic": audit_dic,
                   'revise': revise, "flow_dict": flow_dict, "applicat_time": datetime.now().strftime("%Y-%m-%d"), "Telephone": request.user.mobile}
        return render(request, 'logistics/ServiceProcurementDraft.html', context)

    def post(self, request):
        applic_id = request.POST.get("id", '')
        ApplicationReason = request.POST.get("ApplicationReason", '')
        ApplicationType = request.POST.get("ApplicationType", '')
        ServiceContent = request.POST.get("ServiceContent", '')
        BudgetAmount = request.POST.get("BudgetAmount", '')
        AmountWords = request.POST.get("AmountWords", '')
        fj_number = request.POST.get('fj_number', '')
        if applic_id:
            obj = PurchasingRequisition.objects.get(id=applic_id)
            obj.ApplicationReason = ApplicationReason
            obj.ApplicationType = ApplicationType
            obj.ServiceContent = ServiceContent
            obj.BudgetAmount = BudgetAmount
            obj.AmountWords = AmountWords
            message_str = "修改成功！"
        else:
            obj = PurchasingRequisition.objects.create(apply_user=request.user, ApplicationReason=ApplicationReason,
                                                       ApplicationType=ApplicationType, company=request.user.company,
                                                       ServiceContent=ServiceContent, BudgetAmount=BudgetAmount,
                                                       AmountWords=AmountWords, fj_number=fj_number)
            message_str = "创建成功！"
        obj.state = 'draft'
        obj.save()
        returnData = {'code': 200, 'message': message_str}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class ServiceProcurementDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")

        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = PurchasingRequisition.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.purchasingrequisitionrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.purchasingrequisitionrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state, 'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                               audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post, 'department': request.user.company.name, 'obj': obj, "audit_dic": audit_dic,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_edit": "true" if (obj.state in ['six'] and request.user == obj.apply_user) or revise else 'false', 'file_list': file_list,
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'six'] and request.user == obj.apply_user else 'false', 'revise': revise, "flow_dict": flow_dict,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
        }
        return render(request, 'logistics/ServiceProcurementDetail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "服务采购")
        except:
            pass
        obj = PurchasingRequisition.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        next_audit_obj = None
        if obj.state == 'one':
            audit_obj = obj.purchasingrequisitionrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.purchasingrequisitionrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
            else:
                obj_state = 'six'
        elif obj.state == 'two':
            audit_obj = obj.purchasingrequisitionrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.purchasingrequisitionrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
            else:
                obj_state = 'six'
        elif obj.state == 'three':
            audit_obj = obj.purchasingrequisitionrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.purchasingrequisitionrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
            else:
                obj_state = 'six'
        elif obj.state == 'four':
            audit_obj = obj.purchasingrequisitionrecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
                three_appave = Company.objects.get(id=27).head_people
                MakeCopy.objects.create(recipient=three_appave, process_id=obj.id, type='d')
            else:
                obj_state = 'six'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.can_revise = '0'
        obj.state = obj_state
        if obj_state == 'six':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "服务采购"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.ApplicationReason[:15] + "……" if len(obj.ApplicationReason) > 15 else obj.ApplicationReason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ServiceProcurementStop(View):
    def post(self, request):
        delete_type = request.POST.get("type", None)
        sub_id = request.POST.get("id", None)
        state = request.POST.get("state", None)
        if delete_type:
            obj = PurchasingRequisition.objects.get(id=int(sub_id))
            if obj.state not in ['draft', 'six', 'stop']:
                returnDict = {'code': 400, 'message': '删除失败！只有草稿或退回流程可以删除。'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            MakeCopy.objects.filter(type='d', process_id=sub_id).delete()
            PurchasingRequisitionRecord.objects.filter(purchasing_requisition_id=obj).delete()
            obj.audit_users_already.clear()
            obj.current_audit_users.clear()
            obj.delete()
        else:
            obj = PurchasingRequisition.objects.get(id=int(sub_id))
            obj.state = state
            obj.current_audit_users.clear()
            obj.save()
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

"""物资采购申请流程"""
class GoodsProcureList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'logistics/GoodsProcureList.html', {'realname': real_name, 'position': position, 'department': department, "table_name": "GoodsProcure"})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_value", '')
        objs = GoodsProcure.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(company__name__contains=search_value), apply_user=request.user).order_by('-create_time')

        data_list = [
            {'id': obj.id, 'apply_user': obj.apply_user.real_name, 'create_time': obj.create_time.strftime("%Y-%m-%d"), 'PurchaseReason': obj.PurchaseReason,
             'ApplicationType': '紧急' if obj.ApplicationType == '1' else '非紧急' if obj.ApplicationType == '2' else '', 'GoodsName': obj.GoodsName,
             'custom_made_value': "是" if obj.custom_made_value == '1' else "否" if obj.custom_made_value == '0' else "", 'BudgetAmount': obj.BudgetAmount,
             'state': obj.get_state_str(), 'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'url': f"<a href='GoodsProcureDraft.html?id={obj.id}'>编辑</a>" if obj.get_state_str() == '草稿'
             else (f"<a href='GoodsProcureDetail.html?id={obj.id}'>查看</a> | <a href='GoodsProcureDetail.html?revise=true&id={obj.id}'>修改</a>" if (obj.can_revise == '1' and obj.state in ['one', 'two', 'three', 'four'])
             else (f"<a href='GoodsProcureDetail.html?id={obj.id}'>查看</a>" if obj.state == 'stop'
             else f"<a href='GoodsProcureDetail.html?id={obj.id}'>查看</a>"))} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class GoodsProcureIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'logistics/GoodsProcureIndex.html', {'realname': real_name, 'position': position, 'department': department,
                     "applicat_time": datetime.now().strftime("%Y-%m-%d"), "Telephone": request.user.mobile, "uuid": uuid.uuid4()})

    def post(self, request):
        applic_id = request.POST.get("id", '')
        PurchaseReason = request.POST.get("PurchaseReason", '')
        ApplicationType = request.POST.get("ApplicationType", '')
        GoodsName = request.POST.get("GoodsName", '')
        GoodsNumber = request.POST.get("GoodsNumber", '')
        MaterialQuality = request.POST.get("MaterialQuality", '')
        OtherRequirements = request.POST.get("OtherRequirements", '')
        fj_number = request.POST.get("fj_number", '')
        admin_flag = request.POST.get("admin", '')
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "货物采购")
        except:
            pass
        if applic_id:
            obj = GoodsProcure.objects.get(id=applic_id)
            obj.PurchaseReason = PurchaseReason
            obj.ApplicationType = ApplicationType
            obj.GoodsName = GoodsName
            obj.GoodsNumber = GoodsNumber
            obj.MaterialQuality = MaterialQuality
            obj.OtherRequirements = OtherRequirements
            obj.save()
            message_str = "修改成功！"
        else:
            obj = GoodsProcure.objects.create(apply_user=request.user, PurchaseReason=PurchaseReason, ApplicationType=ApplicationType, company=request.user.company,
                                              GoodsName=GoodsName, GoodsNumber=GoodsNumber, MaterialQuality=MaterialQuality, OtherRequirements=OtherRequirements, fj_number=fj_number)
            message_str = "创建成功！"

        if not admin_flag:
            obj.current_audit_users.clear()
            obj.goodsprocurerecord_set.filter(state='unaudit').delete()

            one_appave = Staffing.objects.get(station='总务科采购人').post_personnel.all().first()
            GoodsProcureRecord.objects.create(node='one', state='unaudit', audit_people=one_appave, purchasing_requisition_id=obj)
            obj.state = "one"
            obj.current_audit_users.add(one_appave)

            two_appave = request.user.company.head_people
            GoodsProcureRecord.objects.create(node='two', state='unaudit', audit_people=two_appave, purchasing_requisition_id=obj)

            three_appave = request.user.company.leaders_id
            GoodsProcureRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, purchasing_requisition_id=obj)

            four_appave = Company.objects.get(id=27).head_people
            GoodsProcureRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, purchasing_requisition_id=obj)

            five_appave = Company.objects.get(id=27).leaders_id
            GoodsProcureRecord.objects.create(node='five', state='unaudit', audit_people=five_appave, purchasing_requisition_id=obj)
            obj.save()
            # ********************************************** 发送小程序推送 ******************************************
            topic_type = "货物采购"
            applicant = obj.apply_user.real_name
            ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = obj.PurchaseReason[:15] + "……" if len(obj.PurchaseReason) > 15 else obj.PurchaseReason
            for jj in obj.current_audit_users.all():
                try:
                    RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
        returnData = {'code': 200, 'message': message_str}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class GoodsProcureDraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = GoodsProcure.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post, "file_list": file_list,
                   'department': request.user.company.name, 'obj': obj, "audit_dic": audit_dic,
                   'revise': revise, "flow_dict": flow_dict, "applicat_time": datetime.now().strftime("%Y-%m-%d")}
        return render(request, 'logistics/GoodsProcureDraft.html', context)

    def post(self, request):
        applic_id = request.POST.get("id", '')
        PurchaseReason = request.POST.get("PurchaseReason", '')
        ApplicationType = request.POST.get("ApplicationType", '')
        GoodsName = request.POST.get("GoodsName", '')
        GoodsNumber = request.POST.get("GoodsNumber", '')
        MaterialQuality = request.POST.get("MaterialQuality", '')
        OtherRequirements = request.POST.get("OtherRequirements", '')
        fj_number = request.POST.get("fj_number", '')

        if applic_id:
            obj = GoodsProcure.objects.get(id=applic_id)
            obj.PurchaseReason = PurchaseReason
            obj.ApplicationType = ApplicationType
            obj.GoodsName = GoodsName
            obj.GoodsNumber = GoodsNumber
            obj.MaterialQuality = MaterialQuality
            obj.OtherRequirements = OtherRequirements
            obj.save()
            message_str = "修改成功！"
        else:
            obj = GoodsProcure.objects.create(apply_user=request.user, PurchaseReason=PurchaseReason,
                                              ApplicationType=ApplicationType, company=request.user.company,
                                              GoodsName=GoodsName, fj_number=fj_number,
                                              GoodsNumber=GoodsNumber, MaterialQuality=MaterialQuality,
                                              OtherRequirements=OtherRequirements)
            message_str = "创建成功！"
        obj.state = 'draft'
        obj.save()
        returnData = {'code': 200, 'message': message_str}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class GoodsProcureDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = GoodsProcure.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.goodsprocurerecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                                  audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.goodsprocurerecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state, 'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': request.user.real_name, 'position': request.user.post, "file_list": file_list, 'department': request.user.company.name, 'obj': obj, "audit_dic": audit_dic,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four', 'five'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_edit": "true" if (obj.state in ['six'] and request.user == obj.apply_user) or revise else 'false', 'logistics_fill': 'true' if obj.BudgetAmount != '' else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user == obj.apply_user else 'false',
                   'revise': revise, "flow_dict": flow_dict, 'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        if obj.id > 47:
            return render(request, 'logistics/GoodsProcureDetailNew.html', context)
        else:
            return render(request, 'logistics/GoodsProcureDetail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "货物采购")
        except:
            pass
        obj = GoodsProcure.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.id <= 47:
            next_audit_obj = None
            if obj.state == 'one':
                audit_obj = obj.goodsprocurerecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    next_audit_obj = obj.goodsprocurerecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                else:
                    obj_state = 'six'
            elif obj.state == 'two':
                audit_obj = obj.goodsprocurerecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    next_audit_obj = obj.goodsprocurerecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                else:
                    obj_state = 'six'
            elif obj.state == 'three':
                audit_obj = obj.goodsprocurerecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    next_audit_obj = obj.goodsprocurerecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                else:
                    obj_state = 'six'
            elif obj.state == 'four':
                audit_obj = obj.goodsprocurerecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    obj_state = 'seven'
                    three_appave = Company.objects.get(id=27).head_people
                    MakeCopy.objects.create(recipient=three_appave, process_id=obj.id, type='e')
                else:
                    obj_state = 'six'
            else:
                returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            audit_obj.update_time = datetime.now()
            audit_obj.state = state
            audit_obj.audit_note = audit_note
            audit_obj.save()
            obj.can_revise = '0'
            obj.state = obj_state
            if obj_state == 'six':
                obj.current_audit_users.add(obj.apply_user)
            if next_audit_obj:
                obj.current_audit_users.add(next_audit_obj.audit_people)
            obj.save()
        else:
            if obj.state == 'one':
                audit_obj = obj.goodsprocurerecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    trade_union_upload_file(request, obj, 0)

                    custom_made_value = request.POST.get("custom_made_value", '')
                    BudgetAmountFill = request.POST.get("BudgetAmountFill", '')
                    AmountWordsFill = request.POST.get("AmountWordsFill", '')
                    GoodsNumberZwkFill = request.POST.get("GoodsNumberZwkFill", '')
                    MaterialQualityZwkFill = request.POST.get("MaterialQualityZwkFill", '')
                    obj.custom_made_value = custom_made_value
                    obj.BudgetAmount = BudgetAmountFill
                    obj.AmountWords = AmountWordsFill
                    obj.MaterialQualityZwk = MaterialQualityZwkFill
                    obj.GoodsNumberZwk = GoodsNumberZwkFill
                    next_audit_record = obj.goodsprocurerecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'six'
                    obj.current_audit_users.add(obj.apply_user)
            elif obj.state == 'two':
                audit_obj = obj.goodsprocurerecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    next_audit_record = obj.goodsprocurerecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'six'
                    obj.current_audit_users.add(obj.apply_user)
            elif obj.state == 'three':
                audit_obj = obj.goodsprocurerecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    next_audit_record = obj.goodsprocurerecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'six'
                    obj.current_audit_users.add(obj.apply_user)
            elif obj.state == 'four':
                audit_obj = obj.goodsprocurerecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    next_audit_record = obj.goodsprocurerecord_set.filter(node='five', state='unaudit').first()
                    obj_state = 'five'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'six'
                    obj.current_audit_users.add(obj.apply_user)
            elif obj.state == 'five':
                audit_obj = obj.goodsprocurerecord_set.filter(node='five', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    obj_state = 'seven'
                    make_copy_appave = Company.objects.get(id=27).head_people
                    MakeCopy.objects.create(recipient=make_copy_appave, process_id=obj.id, type='e')
                else:
                    obj_state = 'six'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            audit_obj.update_time = datetime.now()
            audit_obj.state = state
            audit_obj.audit_note = audit_note
            audit_obj.save()
            obj.can_revise = '0'
            obj.state = obj_state
            obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "货物采购"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.PurchaseReason[:15] + "……" if len(obj.PurchaseReason) > 15 else obj.PurchaseReason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class GoodsProcureStop(View):
    def post(self, request):
        delete_type = request.POST.get("type", None)
        sub_id = request.POST.get("id", None)
        state = request.POST.get("state", None)
        if delete_type:
            obj = GoodsProcure.objects.get(id=int(sub_id))
            if obj.state not in ['draft', 'six', 'stop']:
                returnDict = {'code': 400, 'message': '删除失败！只有草稿或退回流程可以删除。'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            MakeCopy.objects.filter(type='e', process_id=sub_id).delete()
            GoodsProcureRecord.objects.filter(purchasing_requisition_id=obj).delete()
            obj.audit_users_already.clear()
            obj.current_audit_users.clear()
            obj.delete()
        else:
            obj = GoodsProcure.objects.get(id=int(sub_id))
            obj.state = state
            obj.current_audit_users.clear()
            obj.save()
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

"""维修改造项目申请"""
class MaintenanceRenovationList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'logistics/MaintenanceRenovationList.html', {'realname': real_name, 'position': position, 'department': department, "table_name": "GoodsProcure"})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_value", '')
        objs = MaintenanceRenovation.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(company__name__contains=search_value), apply_user=request.user).order_by('-create_time')

        data_list = [
            {'id': obj.id, 'apply_user': obj.apply_user.real_name, 'create_time': obj.create_time.strftime("%Y-%m-%d"), 'EntryName': obj.EntryName,
             'ApplicationReason': obj.ApplicationReason, 'CostEstimating': obj.CostEstimating, 'state': obj.get_state_str(), 'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'url': f"<a href='MaintenanceRenovationDraft.html?id={obj.id}'>编辑</a>" if obj.get_state_str() == '草稿'
             else (f"<a href='MaintenanceRenovationDetail.html?id={obj.id}'>查看</a> | <a href='MaintenanceRenovationDetail.html?revise=true&id={obj.id}'>修改</a>" if (obj.can_revise == '1' and obj.state in ['one', 'two', 'three', 'four'])
             else (f"<a href='MaintenanceRenovationDetail.html?id={obj.id}'>查看</a>" if obj.state == 'stop'
             else f"<a href='MaintenanceRenovationDetail.html?id={obj.id}'>查看</a>"))} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class MaintenanceRenovationIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'logistics/MaintenanceRenovationIndex.html', {'realname': real_name, 'position': position, 'department': department,
               "applicat_time": datetime.now().strftime("%Y-%m-%d"), "Telephone": request.user.mobile, "uuid": uuid.uuid4()})

    def post(self, request):
        applic_id = request.POST.get("id", '')
        ApplicationReason = request.POST.get("ApplicationReason", '')
        note = request.POST.get("Note", '')
        fj_number = request.POST.get("fj_number", '')
        admin_flag = request.POST.get("admin", '')
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "维修改造")
        except:
            pass
        if applic_id:
            obj = MaintenanceRenovation.objects.get(id=applic_id)
            obj.ApplicationReason = ApplicationReason
            obj.note = note
            obj.save()
            message_str = "修改成功！"
        else:
            obj = MaintenanceRenovation.objects.create(apply_user=request.user, company=request.user.company, fj_number=fj_number,
            ApplicationReason=ApplicationReason, note=note)
            message_str = "创建成功！"

        if not admin_flag:
            obj.current_audit_users.clear()
            obj.maintenancerenovationrecord_set.filter(state='unaudit').delete()

            one_appave = Company.objects.get(id=27).head_people
            MaintenanceRenovationRecord.objects.create(node='one', state='unaudit', audit_people=one_appave, purchasing_requisition_id=obj)
            obj.state = "one"
            obj.current_audit_users.add(one_appave)

            two_appave = obj.company.head_people
            MaintenanceRenovationRecord.objects.create(node='two', state='unaudit', audit_people=two_appave, purchasing_requisition_id=obj)

            three_appave = obj.company.leaders_id
            MaintenanceRenovationRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, purchasing_requisition_id=obj)

            four_appave = Company.objects.get(id=27).leaders_id
            MaintenanceRenovationRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, purchasing_requisition_id=obj)
            obj.save()
            # ********************************************** 发送小程序推送 ******************************************
            topic_type = "维修改造"
            applicant = obj.apply_user.real_name
            ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = obj.ApplicationReason[:15] + "……" if len(obj.ApplicationReason) > 15 else obj.ApplicationReason
            for jj in obj.current_audit_users.all():
                try:
                    RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
        returnData = {'code': 200, 'message': message_str}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class MaintenanceRenovationDraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = MaintenanceRenovation.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post, 'file_list': file_list,
                   'department': request.user.company.name, 'obj': obj, "audit_dic": audit_dic,
                   'revise': revise, "flow_dict": flow_dict, "applicat_time": datetime.now().strftime("%Y-%m-%d"),
                   "Telephone": request.user.mobile}
        return render(request, 'logistics/MaintenanceRenovationDraft.html', context)

    def post(self, request):
        applic_id = request.POST.get("id", '')
        ApplicationReason = request.POST.get("ApplicationReason", '')
        fj_number = request.POST.get("fj_number", '')
        note = request.POST.get("Note", '')

        if applic_id:
            obj = MaintenanceRenovation.objects.get(id=applic_id)
            obj.ApplicationReason = ApplicationReason
            obj.note = note
            obj.save()
            message_str = "修改成功！"
        else:
            obj = MaintenanceRenovation.objects.create(apply_user=request.user, note=note, company=request.user.company, fj_number=fj_number,
            ApplicationReason=ApplicationReason)
            message_str = "保存成功！"

        obj.state = 'draft'
        obj.save()
        returnData = {'code': 200, 'message': message_str}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class MaintenanceRenovationDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = MaintenanceRenovation.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.maintenancerenovationrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                                  audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.maintenancerenovationrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state, 'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post, 'file_list': file_list,
                   'department': request.user.company.name, 'obj': obj, "audit_dic": audit_dic, 'revise': revise, "flow_dict": flow_dict,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_edit": "true" if (obj.state in ['six'] and request.user == obj.apply_user) or revise else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'six'] and request.user == obj.apply_user else 'false',
                   'zwk_content': 'true' if obj.state in ['two', 'three', 'four', 'seven'] else 'false',
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        if obj.id < 57:
            return render(request, 'logistics/MaintenanceRenovationDetail.html', context)
        else:
            return render(request, 'logistics/MaintenanceRenovationDetailNew.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "维修改造")
        except:
            pass
        obj = MaintenanceRenovation.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.remove(request.user)
        next_audit_obj = None
        if obj.state == 'one':
            EntryName = request.POST.get('EntryName', '')
            CostEstimating = request.POST.get('CostEstimating', '')
            BudgetDetails = request.POST.get('BudgetDetails', '')
            DurationRequirements = request.POST.get('DurationRequirements', '')
            TrialDate = request.POST.get('TrialDate', '')
            obj.EntryName = EntryName
            obj.CostEstimating = CostEstimating
            obj.DurationRequirements = DurationRequirements
            obj.BudgetDetails = BudgetDetails
            obj.TrialDate = TrialDate

            audit_obj = obj.maintenancerenovationrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.maintenancerenovationrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
            else:
                obj_state = 'six'
        elif obj.state == 'two':
            audit_obj = obj.maintenancerenovationrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.maintenancerenovationrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
            else:
                obj_state = 'six'
        elif obj.state == 'three':
            audit_obj = obj.maintenancerenovationrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.maintenancerenovationrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
            else:
                obj_state = 'six'
        elif obj.state == 'four':
            audit_obj = obj.maintenancerenovationrecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
                three_appave = Company.objects.get(id=27).head_people
                MakeCopy.objects.create(recipient=three_appave, process_id=obj.id, type='g')
            else:
                obj_state = 'six'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.can_revise = '0'
        obj.state = obj_state
        if obj_state == 'six':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "维修改造"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.ApplicationReason[:15] + "……" if len(obj.ApplicationReason) > 15 else obj.ApplicationReason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class MaintenanceRenovationStop(View):
    def post(self, request):
        delete_type = request.POST.get("type", None)
        sub_id = request.POST.get("id", None)
        state = request.POST.get("state", None)
        if delete_type:
            obj = MaintenanceRenovation.objects.get(id=int(sub_id))
            if obj.state not in ['draft', 'six', 'stop']:
                returnDict = {'code': 400, 'message': '删除失败！只有草稿或退回流程可以删除。'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            MakeCopy.objects.filter(type='g', process_id=sub_id).delete()
            MaintenanceRenovationRecord.objects.filter(purchasing_requisition_id=obj).delete()
            obj.audit_users_already.clear()
            obj.current_audit_users.clear()
            obj.delete()
        else:
            obj = MaintenanceRenovation.objects.get(id=int(sub_id))
            obj.state = state
            obj.current_audit_users.clear()
            obj.save()
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

"""计算机及相关设备购置"""
class ComputerDeviceList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'logistics/ComputerDeviceList.html', {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_value", '')
        objs = ComputerDevice.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(company__name__contains=search_value), apply_user=request.user).order_by('-create_time')

        data_list = [
            {'id': obj.id, 'apply_user': obj.apply_user.real_name, 'create_time': obj.create_time.strftime("%Y-%m-%d"),
             'ApplicationReason': obj.ApplicationReason, 'state': obj.get_state_str(), 'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'url': f"<a href='ComputerDeviceDraft.html?id={obj.id}'>编辑</a>" if obj.get_state_str() == '草稿'
             else (f"<a href='ComputerDeviceDetail.html?id={obj.id}'>查看</a> | <a href='ComputerDeviceDetail.html?revise=true&id={obj.id}'>修改</a>" if (obj.can_revise == '1' and obj.state in ['one', 'two', 'three', 'four'])
             else (f"<a href='ComputerDeviceDetail.html?id={obj.id}'>查看</a>" if obj.state == 'stop'
             else f"<a href='ComputerDeviceDetail.html?id={obj.id}'>查看</a>"))} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ComputerDeviceIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'logistics/ComputerDeviceIndex.html', {'realname': real_name, 'position': position, 'department': department, 'uuid': uuid.uuid4(),
                                                                      "applicat_time": datetime.now().strftime("%Y-%m-%d"), "Telephone": request.user.mobile})

    def post(self, request):
        applic_id = request.POST.get("id", '')
        ApplicationReason = request.POST.get("ApplicationReason", '')
        ApplicationDetail = request.POST.get("ApplicationDetail", '')
        admin_flag = request.POST.get("admin", '')
        fj_number = request.POST.get("fj_number", '')
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "计算机及相关设备购置")
        except:
            pass
        if applic_id:
            obj = ComputerDevice.objects.get(id=applic_id)
            obj.ApplicationReason = ApplicationReason
            obj.ApplicationDetail = ApplicationDetail
            obj.save()
            message_str = "修改成功！"
        else:
            obj = ComputerDevice.objects.create(apply_user=request.user, company=request.user.company, ApplicationReason=ApplicationReason, ApplicationDetail=ApplicationDetail, fj_number=fj_number)
            message_str = "创建成功！"
        if not admin_flag:
            obj.current_audit_users.clear()
            obj.computerdevicerecord_set.filter(state='unaudit').delete()

            one_appave = request.user.company.head_people
            flag = True
            if request.user != one_appave:
                ComputerDeviceRecord.objects.create(node='one', state='unaudit', audit_people=one_appave, purchasing_requisition_id=obj)
                flag = False
                obj.state = "one"
                obj.current_audit_users.add(one_appave)

            two_appave = Company.objects.get(id=31).head_people
            ComputerDeviceRecord.objects.create(node='two', state='unaudit', audit_people=two_appave, purchasing_requisition_id=obj)
            if flag:
                obj.state = "two"
                obj.current_audit_users.add(two_appave)

            three_appave = request.user.company.leaders_id
            ComputerDeviceRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, purchasing_requisition_id=obj)

            four_appave = Company.objects.get(id=31).leaders_id
            ComputerDeviceRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, purchasing_requisition_id=obj)
            obj.save()
            # ********************************************** 发送小程序推送 ******************************************
            topic_type = "后勤管理"
            applicant = obj.apply_user.real_name
            ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = "计算机及相关设备购置"
            for jj in obj.current_audit_users.all():
                try:
                    RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
        returnData = {'code': 200, 'message': message_str}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class ComputerDeviceDraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ComputerDevice.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3], "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post, 'file_list': file_list,
                   'department': request.user.company.name, 'obj': obj, "audit_dic": audit_dic,
                   'revise': revise, "ApplicationDetail": json.loads(obj.ApplicationDetail), "applicat_time": datetime.now().strftime("%Y-%m-%d"),
                   "Telephone": request.user.mobile}
        return render(request, 'logistics/ComputerDeviceDraft.html', context)

    def post(self, request):
        applic_id = request.POST.get("id", '')
        ApplicationReason = request.POST.get("ApplicationReason", '')
        ApplicationDetail = request.POST.get("ApplicationDetail", '')
        fj_number = request.POST.get("fj_number", '')
        if applic_id:
            obj = ComputerDevice.objects.get(id=applic_id)
            obj.ApplicationReason = ApplicationReason
            obj.ApplicationDetail = ApplicationDetail
            obj.save()
            message_str = "修改成功！"
        else:
            obj = ComputerDevice.objects.create(apply_user=request.user, company=request.user.company, ApplicationReason=ApplicationReason, ApplicationDetail=ApplicationDetail, fj_number=fj_number)
            message_str = "创建成功！"
        obj.state = 'draft'
        obj.save()
        returnData = {'code': 200, 'message': message_str}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class ComputerDeviceDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ComputerDevice.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.computerdevicerecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.computerdevicerecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state, 'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3], "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post, 'file_list': file_list, 'department': request.user.company.name, 'obj': obj, "audit_dic": audit_dic,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_edit": "true" if (obj.state in ['six'] and request.user == obj.apply_user) or revise else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'six'] and request.user == obj.apply_user else 'false',
                   'revise': revise, "flow_dict": flow_dict, "ApplicationDetail": json.loads(obj.ApplicationDetail),
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'logistics/ComputerDeviceDetail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "计算机及相关设备购置")
        except:
            pass
        obj = ComputerDevice.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        next_audit_obj = None
        if obj.state == 'one':
            audit_obj = obj.computerdevicerecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.computerdevicerecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
            else:
                obj_state = 'six'
        elif obj.state == 'two':
            audit_obj = obj.computerdevicerecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.computerdevicerecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
            else:
                obj_state = 'six'
        elif obj.state == 'three':
            audit_obj = obj.computerdevicerecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.computerdevicerecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
            else:
                obj_state = 'six'
        elif obj.state == 'four':
            audit_obj = obj.computerdevicerecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
                three_appave = Company.objects.get(id=31).head_people
                MakeCopy.objects.create(recipient=three_appave, process_id=obj.id, type='h')
            else:
                obj_state = 'six'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.can_revise = '0'
        obj.state = obj_state
        if obj_state == 'six':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "后勤管理"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = "计算机及相关设备购置"
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ComputerDeviceStop(View):
    def post(self, request):
        delete_type = request.POST.get("type", None)
        sub_id = request.POST.get("id", None)
        state = request.POST.get("state", None)
        if delete_type:
            obj = ComputerDevice.objects.get(id=int(sub_id))
            if obj.state not in ['draft', 'six', 'stop']:
                returnDict = {'code': 400, 'message': '删除失败！只有草稿或退回流程可以删除。'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            MakeCopy.objects.filter(type='h', process_id=sub_id).delete()
            ComputerDeviceRecord.objects.filter(purchasing_requisition_id=obj).delete()
            obj.audit_users_already.clear()
            obj.current_audit_users.clear()
            obj.delete()
        else:
            obj = ComputerDevice.objects.get(id=int(sub_id))
            obj.state = state
            obj.current_audit_users.clear()
            obj.save()
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

"""机密数据外导申请"""
class ConfidentialInformationList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'logistics/ConfidentialInformationList.html', {'realname': real_name, 'position': position, 'department': department, "applicat_time": datetime.now().strftime("%Y-%m-%d"), "Telephone": request.user.mobile})

class ConfidentialInformationIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'logistics/ConfidentialInformationIndex.html', {'realname': real_name, 'position': position, 'department': department, "applicat_time": datetime.now().strftime("%Y-%m-%d"), "Telephone": request.user.mobile})

class ConfidentialInformationDraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'logistics/ConfidentialInformationDraft.html',
                      {'realname': real_name, 'position': position, 'department': department,
                       "applicat_time": datetime.now().strftime("%Y-%m-%d"), "Telephone": request.user.mobile})

class ConfidentialInformationDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'logistics/ConfidentialInformationDetail.html', {'realname': real_name, 'position': position, 'department': department, "applicat_time": datetime.now().strftime("%Y-%m-%d"), "Telephone": request.user.mobile})

class ConfidentialInformationStop(View):
    def post(self, request):
        delete_type = request.POST.get("type", None)
        sub_id = request.POST.get("id", None)
        state = request.POST.get("state", None)
        if delete_type:
            obj = ComputerDevice.objects.get(id=int(sub_id))
            ComputerDeviceRecord.objects.filter(purchasing_requisition_id=obj).delete()
            obj.audit_users_already.clear()
            obj.current_audit_users.clear()
            obj.delete()
        else:
            obj = ComputerDevice.objects.get(id=int(sub_id))
            obj.state = state
            obj.current_audit_users.clear()
            obj.save()
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class BiddingProcurementProjectList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'logistics/BiddingProcurementProjectList.html', {'realname': real_name, 'position': position, 'department': department, "applicat_time": datetime.now().strftime("%Y-%m-%d")})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_value", '')
        objs = BiddingProcurementProject.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(company__name__contains=search_value), apply_user=request.user).order_by('-create_time')

        data_list = [
            {'id': obj.id, 'create_time': obj.create_time.strftime("%Y-%m-%d"), 'company': obj.company.name, 'categories': '工程类' if obj.categories == '1' else '货物类' if obj.categories == '2' else '服务类',
             'ApplicationReason': obj.ApplicationReason, 'budget_amount': obj.budget_amount, 'project_leader': obj.project_leader, 'state': obj.get_state_str(), 'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'url': f"<a href='BiddingProcurementProjectDraft.html?id={obj.id}'>编辑</a>" if obj.get_state_str() == '草稿'
             else (f"<a href='BiddingProcurementProjectDetail.html?id={obj.id}'>查看</a> | <a href='BiddingProcurementProjectDetail.html?revise=true&id={obj.id}'>修改</a>" if (obj.can_revise == '1' and obj.state in ['one', 'two', 'three', 'four', 'five'])
             else (f"<a href='BiddingProcurementProjectDetail.html?id={obj.id}'>查看</a>" if obj.state == 'stop'
             else f"<a href='BiddingProcurementProjectDetail.html?id={obj.id}'>查看</a>"))} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class BiddingProcurementProjectIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'logistics/BiddingProcurementProjectIndex.html', {'realname': real_name, 'position': position, 'department': department, "applicat_time": datetime.now().strftime("%Y-%m-%d"), "Telephone": request.user.mobile, 'uuid': uuid.uuid4()})

    def post(self, request):
        applic_id = request.POST.get("id", '')
        ApplicationReason = request.POST.get('ApplicationReason', '')
        categories = request.POST.get('categories', '')
        budget_amount = request.POST.get('budget_amount', '')
        source = request.POST.get('source', '')
        project_leader = request.POST.get('project_leader', '')
        telephone = request.POST.get('telephone', '')
        fj_number = request.POST.get('uuid', '')
        contact_person = request.POST.get('contact_person', '')
        contact_telephone = request.POST.get('contact_telephone', '')
        project_meeting = request.POST.get('project_meeting', '')
        minutes_number_year = request.POST.get('minutes_number_year', "")
        minutes_number_number = request.POST.get('minutes_number_number', '')
        topic_number = request.POST.get("topic_number", '')
        admin_flag = request.POST.get("admin", '')
        amount_conditions = request.POST.get("amount_conditions", '')
        print(amount_conditions)
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "招标采购项目")
        except:
            pass
        if applic_id:
            obj = BiddingProcurementProject.objects.get(id=applic_id)
            obj.ApplicationReason = ApplicationReason
            obj.categories = categories
            obj.budget_amount = budget_amount
            obj.source = source
            obj.project_leader = project_leader
            obj.telephone = telephone
            obj.contact_person = contact_person
            obj.contact_telephone = contact_telephone
            obj.project_meeting = project_meeting
            obj.minutes_number_year = minutes_number_year
            obj.minutes_number_number = minutes_number_number
            obj.topic_number = topic_number
            obj.amount_conditions = amount_conditions
            obj.save()
            message_str = "修改成功！"
        else:
            obj = BiddingProcurementProject.objects.create(apply_user=request.user, company=request.user.company, ApplicationReason=ApplicationReason, categories=categories, fj_number=fj_number, amount_conditions=amount_conditions,
                                                           budget_amount=budget_amount, source=source, project_leader=project_leader, telephone=telephone, contact_person=contact_person, topic_number=topic_number,
                                                           contact_telephone=contact_telephone, project_meeting=project_meeting, minutes_number_year=minutes_number_year, minutes_number_number=minutes_number_number)
            message_str = "创建成功！"

        if not admin_flag:
            if amount_conditions == '0':            # 3万元一下流程节点创建
                obj.current_audit_users.clear()
                obj.biddingprocurementprojectrecord_set.filter(state='unaudit').delete()

                one_appave = request.user.company.head_people
                flag = True
                if request.user != one_appave:
                    BiddingProcurementProjectRecord.objects.create(node='one', state='unaudit', audit_people=one_appave, parent_id=obj)
                    flag = False
                    obj.state = "one"
                    obj.current_audit_users.add(one_appave)

                two_appave = request.user.company.leaders_id
                BiddingProcurementProjectRecord.objects.create(node='two', state='unaudit', audit_people=two_appave, parent_id=obj)
                if flag:
                    obj.state = "two"
                    obj.current_audit_users.add(two_appave)

                three_appave = Company.objects.get(id=9).head_people
                BiddingProcurementProjectRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, parent_id=obj)

                four_appave = Company.objects.get(id=9).leaders_id
                BiddingProcurementProjectRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, parent_id=obj)
                BiddingProcurementProjectRecord.objects.create(node='five', state='unaudit', audit_people=request.user, parent_id=obj)
                BiddingProcurementProjectRecord.objects.create(node='six', state='unaudit', audit_people=three_appave, parent_id=obj)
                obj.save()
            else:
                obj.current_audit_users.clear()
                obj.biddingprocurementprojectrecord_set.filter(state='unaudit').delete()

                one_appave = request.user.company.head_people
                flag = True
                if request.user != one_appave:
                    BiddingProcurementProjectRecord.objects.create(node='one', state='unaudit', audit_people=one_appave, parent_id=obj)
                    flag = False
                    obj.state = "one"
                    obj.current_audit_users.add(one_appave)

                two_appave = request.user.company.leaders_id
                BiddingProcurementProjectRecord.objects.create(node='two', state='unaudit', audit_people=two_appave, parent_id=obj)
                if flag:
                    obj.state = "two"
                    obj.current_audit_users.add(two_appave)

                three_appave = Company.objects.get(id=9).head_people
                BiddingProcurementProjectRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, parent_id=obj)

                four_appave = Company.objects.get(id=9).leaders_id
                BiddingProcurementProjectRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, parent_id=obj)

                five_appave = Staffing.objects.get(station='院长').post_personnel.all().first()
                BiddingProcurementProjectRecord.objects.create(node='five', state='unaudit', audit_people=five_appave, parent_id=obj)
                obj.save()

            # ********************************************** 发送小程序推送 ******************************************
            topic_type = "招标采购"
            applicant = obj.apply_user.real_name
            ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = obj.ApplicationReason[:15] + "……" if len(obj.ApplicationReason) > 15 else obj.ApplicationReason
            for jj in obj.current_audit_users.all():
                try:
                    RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
        returnData = {'code': 200, 'message': message_str}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class BiddingProcurementProjectDraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = BiddingProcurementProject.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.biddingprocurementprojectrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.biddingprocurementprojectrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state,
                     'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note,
                     'audit_time': audit_obj.update_time.strftime(
                         "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                 audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                          os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true',
                   'flow_dict': flow_dict, "revise": revise,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'logistics/BiddingProcurementProjectDraft.html', context)

    def post(self, request):
        applic_id = request.POST.get("id", '')
        ApplicationReason = request.POST.get('ApplicationReason', '')
        categories = request.POST.get('categories', '')
        budget_amount = request.POST.get('budget_amount', '')
        source = request.POST.get('source', '')
        fj_number = request.POST.get('uuid', '')
        project_leader = request.POST.get('project_leader', '')
        telephone = request.POST.get('telephone', '')
        contact_person = request.POST.get('contact_person', '')
        contact_telephone = request.POST.get('contact_telephone', '')
        project_meeting = request.POST.get('project_meeting', '')
        minutes_number_year = request.POST.get('minutes_number_year', "")
        minutes_number_number = request.POST.get('minutes_number_number', '')
        topic_number = request.POST.get("topic_number", '')
        amount_conditions = request.POST.get("amount_conditions", '')

        if applic_id:
            obj = BiddingProcurementProject.objects.get(id=applic_id)
            obj.ApplicationReason = ApplicationReason
            obj.categories = categories
            obj.budget_amount = budget_amount
            obj.source = source
            obj.topic_number = topic_number
            obj.project_leader = project_leader
            obj.telephone = telephone
            obj.contact_person = contact_person
            obj.contact_telephone = contact_telephone
            obj.project_meeting = project_meeting
            obj.minutes_number_year = minutes_number_year
            obj.minutes_number_number = minutes_number_number
            obj.amount_conditions = amount_conditions
            obj.save()
            message_str = "修改成功！"
        else:
            obj = BiddingProcurementProject.objects.create(apply_user=request.user, company=request.user.company, ApplicationReason=ApplicationReason, categories=categories, budget_amount=budget_amount, source=source,
                                                           project_leader=project_leader, telephone=telephone, contact_person=contact_person, contact_telephone=contact_telephone, project_meeting=project_meeting,
                                                           minutes_number_year=minutes_number_year, minutes_number_number=minutes_number_number, fj_number=fj_number, topic_number=topic_number, amount_conditions=amount_conditions)
            message_str = "保存成功！"
        obj.state = 'draft'
        obj.save()
        returnData = {'code': 200, 'message': message_str}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class BiddingProcurementProjectDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = BiddingProcurementProject.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.biddingprocurementprojectrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.biddingprocurementprojectrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                              'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'eight'] and request.user == obj.apply_user else 'false',
                   'flow_dict': flow_dict, "revise": revise,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'logistics/BiddingProcurementProjectDetail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        procurement = request.POST.get("procurement", None)
        approval_leader = request.POST.get("approval_leader", None)
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "招标采购项目")
        except:
            pass
        obj = BiddingProcurementProject.objects.get(id=id)

        if not obj.biddingprocurementprojectrecord_set.filter(node=obj.state, state='unaudit', audit_people=request.user).count():
            returnDict = {'code': 500, 'message': '流程已审核，请勿重复点击！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        next_audit_obj = None
        if obj.state == 'one':
            audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
            else:
                obj_state = 'eight'
        elif obj.state == 'two':
            audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
            else:
                obj_state = 'eight'
        elif obj.state == 'three':
            audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.open_ornot = procurement
            else:
                obj_state = 'eight'
        elif obj.state == 'four':
            audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.biddingprocurementprojectrecord_set.filter(node='five'):
                    next_audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='five', state='unaudit').first()
                    obj_state = 'five'
                else:
                    obj_state = 'seven'
            else:
                obj_state = 'eight'
        elif obj.state == 'five':
            audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='five', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.amount_conditions == '1':
                    obj_state = 'seven'
                    approval_department = obj.company.head_people
                    MakeCopy.objects.create(recipient=approval_department, process_id=obj.id, type='j')
                    zbb_obj = Company.objects.get(id=9)
                    zbb_appave = zbb_obj.head_people
                    MakeCopy.objects.create(recipient=zbb_appave, process_id=obj.id, type='j')
                    MakeCopy.objects.create(recipient=zbb_obj.leaders_id, process_id=obj.id, type='j')
                    MakeCopy.objects.create(recipient=obj.company.leaders_id, process_id=obj.id, type='j')
                else:
                    next_audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='six', state='unaudit').first()
                    obj_state = 'six'
            else:
                obj_state = 'eight'
        elif obj.state == 'six':
            audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='six', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.can_revise = '0'
        obj.state = obj_state
        if obj_state == 'eight':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "招标采购"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.ApplicationReason[:15] + "……" if len(obj.ApplicationReason) > 15 else obj.ApplicationReason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class BiddingProcurementProjectStop(View):
    def post(self, request):
        delete_type = request.POST.get("type", None)
        sub_id = request.POST.get("id", None)
        state = request.POST.get("state", None)
        if delete_type:
            obj = BiddingProcurementProject.objects.get(id=int(sub_id))
            if obj.state not in ['draft', 'six', 'stop']:
                returnDict = {'code': 400, 'message': '删除失败！只有草稿或退回流程可以删除。'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            MakeCopy.objects.filter(type='j', process_id=sub_id).delete()
            BiddingProcurementProjectRecord.objects.filter(parent_id=obj).delete()
            obj.audit_users_already.clear()
            obj.current_audit_users.clear()
            obj.delete()
        else:
            obj = BiddingProcurementProject.objects.get(id=int(sub_id))
            obj.state = state
            obj.current_audit_users.clear()
            obj.save()
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class test_code(View):
    def get(self, request):
        signature = request.GET.get('signature', '')
        timestamp = request.GET.get('timestamp', '')
        nonce = request.GET.get('nonce', '')
        token = 'sada123'  # 这里填写你在微信开发者后台设置的Token
        echostr = request.GET.get('echostr', '')
        if check_signature(signature, timestamp, nonce, token):
            return HttpResponse(echostr)
        else:
            return HttpResponse('Invalid signature')

def check_signature(signature, timestamp, nonce, token):
    """
    验证请求是否合法
    """
    tmp_lst = [token, timestamp, nonce]
    tmp_lst.sort()
    tmp_str = ''.join(tmp_lst)
    tmp_str = hashlib.sha1(tmp_str.encode('utf8')).hexdigest()
    if tmp_str == signature:
        return True
    else:
        return False

class PermissionRequirementsList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'logistics/PermissionRequirementsList.html', {'realname': real_name, 'position': position, 'department': department, "applicat_time": datetime.now().strftime("%Y-%m-%d"), "Telephone": request.user.mobile})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_value", '')
        objs = ProcessModification.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(company__name__contains=search_value) | Q(reason__contains=search_value), apply_user=request.user).order_by('-create_time')

        data_list = [
            {'id': obj.id, 'apply_user': obj.apply_user.real_name, 'create_time': obj.create_time.strftime("%Y-%m-%d"), 'reason': obj.reason,
             'urgency_level': obj.urgency_level, 'state': obj.get_state_str(), 'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'url': f"<a href='PermissionRequirementsDraft.html?id={obj.id}'>编辑</a>" if obj.get_state_str() == '草稿'
             else (f"<a href='PermissionRequirementsDetail.html?id={obj.id}'>查看</a> | <a href='PermissionRequirementsDetail.html?revise=true&id={obj.id}'>修改</a>" if (obj.can_revise == '1' and obj.state in ['one', 'two', 'three', 'four', 'five'])
             else (f"<a href='PermissionRequirementsDetail.html?id={obj.id}'>查看</a>" if obj.state == 'stop'
             else f"<a href='PermissionRequirementsDetail.html?id={obj.id}'>查看</a>"))} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class PermissionRequirementsIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'logistics/PermissionRequirementsIndex.html', {'realname': real_name, 'position': position, 'department': department, "applicat_time": datetime.now().strftime("%Y-%m-%d"), "Telephone": request.user.mobile})

class TenderingSigningList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'logistics/tendering_signing_list.html', {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        objs = TenderingSigning.objects.filter(apply_user=request.user).order_by('-create_time')

        data_list = [
            {'id': obj.id, 'entry_name': obj.entry_name, 'budget_amount': obj.budget_amount, 'categories': obj.get_procurement(), 'winning_bidder': obj.winning_bidder, 'state': obj.get_state_str(), 'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'url': f"<a href='tendering_signing_draft.html?id={obj.id}'>编辑</a>" if obj.get_state_str() == '草稿'
             else (f"<a href='tendering_signing_detail.html?id={obj.id}'>查看</a> | <a href='tendering_signing_detail.html?revise=true&id={obj.id}'>修改</a>" if (obj.can_revise == '1' and obj.state in ['one', 'two', 'three'])
             else (f"<a href='tendering_signing_detail.html?id={obj.id}'>查看</a>" if obj.state == 'stop'
             else f"<a href='tendering_signing_detail.html?id={obj.id}'>查看</a>"))} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class TenderingSigningIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'logistics/tendering_signing_index.html', {'realname': real_name, 'position': position, 'department': department, 'uuid': uuid.uuid4()})

    def post(self, request):
        flow_id = request.POST.get("id", '')
        entry_name = request.POST.get('entry_name', '')
        budget_amount = request.POST.get('budget_amount', '')
        minutes_number = request.POST.get('minutes_number', '')
        procurement = request.POST.get('procurement', '')
        open_time = request.POST.get('open_time', '')
        more_than = request.POST.get('more_than', '')
        fj_number = request.POST.get('uuid', '')
        winning_bidder = request.POST.get('winning_bidder', '')
        winning_money = request.POST.get('winning_money', '')

        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "招标结果汇报会签")
        except:
            pass
        if flow_id:
            obj = TenderingSigning.objects.get(id=flow_id)
            obj.entry_name = entry_name
            obj.budget_amount = budget_amount
            obj.minutes_number = minutes_number
            obj.procurement = procurement
            obj.open_time = open_time
            obj.more_than = more_than
            obj.winning_bidder = winning_bidder
            obj.winning_money = winning_money
            obj.save()
            message_str = "修改成功！"
        else:
            obj = TenderingSigning.objects.create(apply_user=request.user, company=request.user.company, entry_name=entry_name, budget_amount=budget_amount,
                                                           fj_number=fj_number, minutes_number=minutes_number, procurement=procurement, open_time=open_time, more_than=more_than,
                                                           winning_bidder=winning_bidder, winning_money=winning_money)
            message_str = "创建成功！"

        obj.current_audit_users.clear()
        obj.tenderingsigningrecord_set.filter(state='unaudit').delete()

        one_appave = request.user.company.head_people
        flag = True
        if request.user != one_appave:
            TenderingSigningRecord.objects.create(node='one', state='unaudit', audit_people=one_appave, parent_id=obj)
            flag = False
            obj.state = "one"
            obj.current_audit_users.add(one_appave)

        two_appave = Company.objects.get(id=9).leaders_id
        TenderingSigningRecord.objects.create(node='two', state='unaudit', audit_people=two_appave, parent_id=obj)
        if flag:
            obj.state = "two"
            obj.current_audit_users.add(two_appave)

        three_step = Staffing.objects.get(station='招标会签20万以下').post_personnel.all()
        for three_people in three_step:
            TenderingSigningRecord.objects.create(node='three', state='unaudit', audit_people=three_people, parent_id=obj)

        yz_obj = Staffing.objects.get(station='院长').post_personnel.all().first()
        TenderingSigningRecord.objects.create(node='four', state='unaudit', audit_people=yz_obj, parent_id=obj)

        if more_than == '1':
            five_step = Staffing.objects.get(station='招标会签20万以上').post_personnel.all()
            for five_people in five_step:
                TenderingSigningRecord.objects.create(node='five', state='unaudit', audit_people=five_people, parent_id=obj)

        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "招标结果汇报会签"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.entry_name[:15] + "……" if len(obj.entry_name) > 15 else obj.entry_name
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': message_str}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class TenderingSigningDraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = TenderingSigning.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.tenderingsigningrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.tenderingsigningrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state,
                     'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note,
                     'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list, 'is_edit': 'true', 'flow_dict': flow_dict, "revise": revise,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'logistics/tendering_signing_draft.html', context)

    def post(self, request):
        flow_id = request.POST.get("id", '')
        entry_name = request.POST.get('entry_name', '')
        budget_amount = request.POST.get('budget_amount', '')
        minutes_number = request.POST.get('minutes_number', '')
        procurement = request.POST.get('procurement', '')
        open_time = request.POST.get('open_time', '')
        more_than = request.POST.get('more_than', '')
        fj_number = request.POST.get('uuid', '')
        winning_bidder = request.POST.get('winning_bidder', '')
        winning_money = request.POST.get('winning_money', '')

        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "招标结果汇报会签")
        except:
            pass
        if flow_id:
            obj = TenderingSigning.objects.get(id=flow_id)
            obj.entry_name = entry_name
            obj.budget_amount = budget_amount
            obj.minutes_number = minutes_number
            obj.procurement = procurement
            obj.open_time = open_time
            obj.more_than = more_than
            obj.winning_bidder = winning_bidder
            obj.winning_money = winning_money
            obj.save()
            message_str = "修改成功！"
        else:
            obj = TenderingSigning.objects.create(apply_user=request.user, company=request.user.company, entry_name=entry_name, budget_amount=budget_amount, fj_number=fj_number,
            minutes_number=minutes_number, procurement=procurement, open_time=open_time, more_than=more_than, winning_bidder=winning_bidder, winning_money=winning_money)
            message_str = "创建成功！"
        obj.state = "draft"
        obj.save()
        returnDict = {'code': 200, 'message': message_str}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class TenderingSigningDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = TenderingSigning.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.tenderingsigningrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.tenderingsigningrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state,
                     'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note,
                     'audit_time': audit_obj.update_time.strftime(
                         "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                 audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        flow_dict['three']['apply_people'] = flow_dict['three']['apply_people'] + "," + flow_dict['four']['apply_people']
        if "five" in flow_dict:
            flow_dict['three']['apply_people'] = flow_dict['three']['apply_people'] + "," + flow_dict['five']['apply_people']

        audit_dic['three'] = audit_dic['three'] + audit_dic['four']
        if "five" in audit_dic:
            audit_dic['three'] = audit_dic['three'] + audit_dic['three']

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                          os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list, 'procurement': obj.get_procurement(),
                   'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'eight'] and request.user == obj.apply_user else 'false',
                   'flow_dict': flow_dict, "revise": revise,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'logistics/tendering_signing_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "招标结果汇报会签")
        except:
            pass
        obj = TenderingSigning.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        next_audit_obj = None
        if obj.state == 'one':
            obj.current_audit_users.clear()
            audit_obj = obj.tenderingsigningrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.tenderingsigningrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_obj.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            obj.current_audit_users.clear()
            audit_obj = obj.tenderingsigningrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_list = obj.tenderingsigningrecord_set.filter(node='three', state='unaudit')
                obj_state = 'three'
                for next_audit in next_audit_list:
                    obj.current_audit_users.add(next_audit.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            obj.current_audit_users.remove(request.user)
            audit_obj = obj.tenderingsigningrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if not obj.current_audit_users.all().count():
                    next_audit_list = obj.tenderingsigningrecord_set.filter(node='four', state='unaudit')
                    obj_state = 'four'
                    for next_audit in next_audit_list:
                        obj.current_audit_users.add(next_audit.audit_people)
                else:
                    obj_state = 'three'
            else:
                obj_state = 'eight'

        elif obj.state == 'four':
            obj.current_audit_users.remove(request.user)
            audit_obj = obj.tenderingsigningrecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.more_than == '1':
                    if not obj.current_audit_users.all().count():
                        next_audit_list = obj.tenderingsigningrecord_set.filter(node='five', state='unaudit')
                        obj_state = 'five'
                        for next_audit in next_audit_list:
                            obj.current_audit_users.add(next_audit.audit_people)
                    else:
                        obj_state = 'four'
                else:
                    obj_state = 'end'
            else:
                obj_state = 'eight'

        elif obj.state == 'five':
            obj.current_audit_users.remove(request.user)
            audit_obj = obj.tenderingsigningrecord_set.filter(node='five', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if not obj.current_audit_users.all().count():
                    obj_state = 'end'
                else:
                    obj_state = 'five'
            else:
                obj_state = 'eight'

        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.can_revise = '0'
        obj.state = obj_state
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "招标结果汇报会签"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.entry_name[:15] + "……" if len(obj.entry_name) > 15 else obj.entry_name
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class TenderingSigningStop(View):
    def post(self, request):
        delete_type = request.POST.get("type", None)
        sub_id = request.POST.get("id", None)
        state = request.POST.get("state", None)
        obj = TenderingSigning.objects.get(id=int(sub_id))
        if delete_type:
            TenderingSigningRecord.objects.filter(parent_id=obj).delete()
            obj.audit_users_already.clear()
            obj.current_audit_users.clear()
            obj.delete()
        else:
            obj.state = state
            obj.current_audit_users.clear()
            obj.save()
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")
